package com.cms.recursoshumanos.persistencia;

import net.rim.device.api.system.NonPersistableObjectException;
import net.rim.device.api.system.PersistentObject;
import net.rim.device.api.system.PersistentStore;
import net.rim.device.api.util.Persistable;

/**
 * @author Francisco Julian Trompiz Bergueiro
 *
 * Corporate Mobile Solutions. 2013
 */

public class AbstractPersistableObject implements Persistable{

	private long id;

	protected AbstractPersistableObject(long id){
		this.id = id;
	}
	
	protected boolean hasInfo(long idObj)
	{
		PersistentObject store = PersistentStore.getPersistentObject(idObj);
		try
		{
			synchronized (store) 
			{
				Object elObject = store.getContents();
				if (elObject == null)
				{
					return false;
				}
				else
				{
					return true;
				}
			}
		}
		catch (Exception ee)
		{
			ee.printStackTrace();
			return false;
		}
	}
	protected static Object cargar(long idObj){
		try {
			PersistentObject store = PersistentStore.getPersistentObject(idObj);
			synchronized (store) {
				return store.getContents();
			}
		}
		catch (NonPersistableObjectException ex)
		{
			String elObj = ex.getObject().toString();
			ex.printStackTrace();
		}
		catch (Exception t) 
		{
			t.printStackTrace();
		}
		return null;
	}
	public void guardar(){
		try {
			PersistentObject store = PersistentStore.getPersistentObject(id);
			Object obj = this;
			synchronized (store) {
				store.setContents(obj);
				store.commit();
			}
		}
		catch (NonPersistableObjectException ex)
		{
			String elObj = ex.getObject().toString();
			ex.printStackTrace();
		}
		catch (Exception t) 
		{
			t.printStackTrace();
		}
	}
	
	public void eliminar(){
		try {
			PersistentStore.destroyPersistentObject(id);
		}
		catch (NonPersistableObjectException ex)
		{
			String elObj = ex.getObject().toString();
			ex.printStackTrace();
		}
		catch (Exception t) 
		{
			t.printStackTrace();
		}
	}
	
}
